/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/store/';
import router from '@/router/router'
import {serialize} from '@/utils/util'
import {getToken} from '@/utils/auth'
import {Message} from 'element-ui'
import website from '@/config/website';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import qs from 'qs'
import securityConfig from "@/config/securityConfig";
import {getSecurityData, getSecurityDateClientId, isSecurityDataIgnoreUrl} from "@/store/securityTools";
import startCrypto from "@/start/startCrypto";

axios.defaults.timeout = 10000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
    showSpinner: false
});
const requestMethods = ["get", "delete"]
const requestBodyMethods = ["post", "put"]
//HTTPrequest拦截
axios.interceptors.request.use(config => {
    NProgress.start() // start progress bar
    const meta = (config.meta || {});
    const isToken = meta.isToken === false;
    if (getToken() && !isToken) {
        config.headers[website.Authorization] = 'Bearer ' + getToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    }
    console.log("config", config.url)
    if (securityConfig.securityEnable && requestBodyMethods.includes(config.method) && !isSecurityDataIgnoreUrl(config.url)) {
        let key = getSecurityData();
        if (!key) {
            Message({message: "密钥过期请刷新当前页面", type: 'error'})
            config.cancelToken = new CancelToken((c) => {
                return
            })
            return config;
        }
        let securityDateClientId = getSecurityDateClientId();
        config.headers[securityConfig.securityHeaderKey] = securityDateClientId;
        if (config.data) {
            let data = startCrypto.sm2.encrypt(JSON.stringify(config.data), key)
            config.data = {data}
        }

    }
    //headers中配置serialize为true开启序列化
    // console.log("post请求")
    if (config.method === 'post' && meta.isSerialize === true) {
        if (config.data) {
            config.data = config.data instanceof String ? config.data : serialize(config.data)
        }
    }

    if (requestMethods.includes(config.method)) {
        if (!config.params) {
            if (config.data) {
                config.params = config.data
                config.data = null;
            }
        }
        config.paramsSerializer = function (params) {
            return qs.stringify(params, {arrayFormat: 'repeat'})
        }
    }


    return config
}, error => {
    return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
    NProgress.done();
    // console.log(res)
    const status = Number(res.status) || 200;
    const statusWhiteList = website.statusWhiteList || [];
    const message = res.data.message || '未知错误';
    //如果在白名单里则自行catch逻辑处理
    if (statusWhiteList.includes(status)) return Promise.reject(res);
    // console.log("返回数据", res.data.encrypt)

    //如果是401则跳转到登录页面
    if (status === 401) {
        store.dispatch('FedLogOut').then(() => router.push({path: '/login'}));
        return
    }
    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
        Message({
            message: message,
            type: 'error'
        })
        return Promise.reject(new Error(message))
    }
    if (res.data.encrypt && res.data.data && securityConfig.securityEnable && !isSecurityDataIgnoreUrl(res.config.url)) {
        let decrypt = startCrypto.sm2.decrypt(res.data.data, securityConfig.clientPrivateKey)
        let data
        try {
            data = JSON.parse(decrypt)
        } catch (e) {
            console.log("第一次jsons失败:", e)
            try {
                data = JSON.parse(decrypt)
            } catch (e) {
                console.log("第二次jsons失败:", e)
                res.data.encryptData = decrypt
            }


            // console.error(e);
            // console.log("url:" + res.config.url, res, "解密后数据", decrypt)
        }
        res.data.data = data
    }
    // console.log("res2", res)
    return res;
}, error => {
    NProgress.done();
    // console.log(error)
    return Promise.reject(new Error(error));
})

export default axios;
